package com.lxxie.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Date 2021/10/14 13:40
 * @Created by xielx
 */
@Controller
public class ExportController {

    @RequestMapping("/api/cert/download")
    public void export(@RequestParam("content") String params,@RequestParam("column") String column,
                       HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        HSSFWorkbook wb = new HSSFWorkbook();
        params = URLDecoder.decode(params, "UTF-8");
        column = URLDecoder.decode(column,"UTF-8");
        JSONObject data = JSON.parseObject(params);
        if (data.getInteger("code") != 0) {
            HSSFSheet sheet = wb.createSheet();
            sheet.createRow(0).createCell(0).setCellValue(data.getString("msg"));
            wb.write(response.getOutputStream());
            return;
        }
        try {
            JSONArray rowList = data.getJSONArray("data");
            HSSFSheet sheet = wb.createSheet();
            if (StringUtils.isEmpty(column)) {
                return;
            }
            List<String> headerList = createHeader(sheet,column);
            List<CellRangeAddress> regionList = new ArrayList<>();
            int rowIndex = 1;
            for (int i = 0; i < rowList.size(); i++) {
                JSONObject temp = rowList.getJSONObject(i);
                HSSFRow row = sheet.createRow(rowIndex++);
                row.createCell(0).setCellValue(temp.getString("sfmc"));
                if(null == temp.getInteger("code")){
                    row.createCell(1).setCellValue("未查出");
                    continue;
                }else if (temp.getInteger("code") != 1) {
                    row.createCell(1).setCellValue(temp.getString("msg"));
                    continue;
                }
                //塞入数据
                JSONArray datas = temp.getJSONArray("data");
                for (int index = 0; index < datas.size(); index++) {
                    JSONObject tempData = datas.getJSONObject(index);
                    row = index == 0 ? row : sheet.createRow(rowIndex++);
                    for (int headerIndex = 0; headerIndex < headerList.size(); headerIndex++) {
                        Object val = tempData.get(headerList.get(headerIndex));
                        HSSFCell cell = row.createCell(headerIndex + 1);
                        if(val instanceof Integer){
                            cell.setCellValue((Integer) val);
                        }else if(val instanceof BigDecimal){
                            cell.setCellValue(tempData.getDoubleValue(headerList.get(headerIndex)));
                        }else {
                            cell.setCellValue(tempData.getString(headerList.get(headerIndex)));
                        }
                    }
                }
                //合并单元格
                if (datas.size()>1) {
                    CellRangeAddress region =  new CellRangeAddress(rowIndex-datas.size(),rowIndex-1,0,0);
                    sheet.addMergedRegion(region);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            wb.write(response.getOutputStream());
        }
    }

    private List<String> createHeader(HSSFSheet sheet, String column) {
        HSSFRow row = sheet.createRow(0);
        if (StringUtils.isEmpty(column)) {
            row.createCell(0).setCellValue("无数据");
            return new ArrayList<>();
        }
        List<String> headList = JSON.parseArray(column,String.class);
        int index = 0;
        row.createCell(index++).setCellValue("省份");
        for (String head : headList) {
            row.createCell(index++).setCellValue(head);
        }
        return headList;
    }
}
